"use strict";
define(["commonUI","getTime","template","global","validate"], function (
    commonUI, getTime,template,global
) {

    //当前项目
    var project;
    //当前登录用户
    var user;
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                alert("请先选择项目");
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            if(project.isRemoted==true){
                $("#choose").html('<div class="warn-info">系统设备状态：<span class="warn-btn"></span></div><div class="run-info">运行模式：<span class="btn-switch btn-multiple-state" id="modeSwitch"><span class="btn-state">供冷</span><span class="btn-state">制热</span></span></div><div class="temp-info">温度设定：<span id="temp">'+(project.temperatureSetting == null || project.temperatureSetting == undefined || project.temperatureSetting == "null" ?0 : project.temperatureSetting)+'</span>℃<a id="editTemp">修改</a></div>')
                if(project.systemEquipmentStatus==0 || project.systemEquipmentStatus==null){
                    $(".warn-btn").addClass("close");
                }else if(project.systemEquipmentStatus==1){
                    $(".warn-btn").addClass("open")
                }
                if(project.mode==0){
                    //供冷模式
                    $("#modeSwitch span:eq(0)").addClass("checked")
                    $("#modeSwitch span:eq(1)").removeClass("checked")
                }else{
                    //制热模式
                    $("#modeSwitch span:eq(1)").addClass("checked")
                    $("#modeSwitch span:eq(0)").removeClass("checked")
                }
            }
            this.initText();
            this.initEquipmentMonitorImage();
            this.initBottomData();
            this.eventBind();
            this.initToopTip();
            getTime.getNowDate();
            getTime.getTimeInfo();

        },
        /**
         * 渲染文字内容
         */
        initText: function() {
            user = global.getLoginUser();
            //用户名显示
            $(".userInfo .name").text(user.userName)
            $(".project-info .name").text("项目名称：" + project.name)
        },
        //初始化设备检测图
        initEquipmentMonitorImage:function(){
            document.getElementById("main-img").onload=function(){
                global.get("/web/equipment/equipmentsByProjectId/"+project.id,function(response){
                    var list = response.data.equipments;
                    var mainImg = document.getElementById("main-img");
                    var $mainImg = $("#main-img");
                    list.forEach(equipment => {
                        var rect = document.createElement("div");
                        if(equipment.x1!=null && equipment.x2!=null && equipment.y1!=null && equipment.y2!=null){
                            rect.style.left = (equipment.x1)*$mainImg.width() + "px";
                            rect.style.top = (equipment.y1)*$mainImg.height() +"px";
                            rect.style.width = (equipment.x2-equipment.x1)*$mainImg.width() + "px";
                            rect.style.height = (equipment.y2-equipment.y1)*$mainImg.height() + "px";
                            rect.style.position="absolute";
                            // rect.style.background="white";
                            rect.className="equipment";
                            rect.setAttribute("equipmentId",equipment.id);
                            rect.setAttribute("data-toggle","tooltip");
                            
                            rect.setAttribute("data-placement","top")
                            rect.setAttribute("data-html",true);
                            rect.setAttribute("type","button")
                            mainImg.parentNode.appendChild(rect);
    
                            var circle1 = document.createElement("div");
                            var circle2 = document.createElement("div");
                            if(equipment.status==2){
                                circle1.className="status-yellow"
                                circle2.className="status-yellow-glow"
                            }else if(equipment.status==1){
                                circle1.className="status-red"
                                circle2.className="status-red-glow"
                            }else{
                                circle1.className="status-green"
                                circle2.className="status-green-glow"
                            }
                            circle1.style.position="absolute"
                            circle2.style.position="absolute"
                            circle1.style.left = (equipment.x1)*$mainImg.width() + "px";
                            circle1.style.top = (equipment.y1)*$mainImg.height() +"px";
                            circle2.style.left = (equipment.x1)*$mainImg.width() + "px";
                            circle2.style.top = (equipment.y1)*$mainImg.height() +"px";
                            mainImg.parentNode.appendChild(circle1);
                            mainImg.parentNode.appendChild(circle2);
                        }
                        
                    });
                },null,null,false)
            }
            document.getElementById("main-img").src = global.baseImageUrl+project.image;
       
        },
        initBottomData:function(){
            global.get("web/equipmentMonitor/equipmentMonitorBottomData/"+project.id,function(response){
                var data = response.data;
                $("#outdoorTemperature").text(data.outdoorTemperature + "℃");
                $("#outdoorHumidity").text(data.outdoorHumidity+"%");
                $("#solarRadiation").text(data.solarRadiation)
            })     
        },
        initToopTip: function () {
            $('[data-toggle="tooltip"]').tooltip();
        },
        /** 事件绑定 */
        eventBind: function () {
            $(document).on("click",".warn-btn", function(){
                if($(this).hasClass("close")){ //本来是关闭
                    global.post("/web/rc/start?projectId="+project.id,function(response){
                        if(response.success){
                            $(".warn-btn").removeClass("close").addClass("open");
                            Dialog.toast("启动成功", {"intent":"success"});
                            global.get("/web/project/"+project.id,function (response) {
                                var project = response.data.project;
                                localStorage.setItem("project",JSON.stringify(project));
                            })
                        }else{
                            Dialog.toast("启动失败", {"intent":"warn"});
                        }
                    })
                }else if($(this).hasClass("open")){//本来是关闭状态
                    global.post("/web/rc/stop?projectId="+project.id,function(response){
                        if(response.success){
                            Dialog.toast("关闭成功", {"intent":"success"});
                            $(".warn-btn").removeClass("open").addClass("close")
                            global.get("/web/project/"+project.id,function (response) {
                                var project = response.data.project;
                                localStorage.setItem("project",JSON.stringify(project));
                            })
                        }else{
                            Dialog.toast("关闭失败", {"intent":"warn"});
                        }
                    })
                }
            })
            $(document).on("mouseenter", ".equipment", function () {
                var $this = $(this);
                var equipmentId = $this.attr("equipmentid");
                global.get("/web/equipmentMonitor/simpleMonitorPanel/"+equipmentId,function(response){
                    var equipmentMonitor = response.data.equipmentMonitor;
                    var title = "";
                    if(equipmentMonitor!=null){
                        console.log(equipmentMonitor.length)
                        for(var i=0;i<equipmentMonitor.length;i++){
                            var item = equipmentMonitor[i];
                            title += item.deviceName + ":" + item.data + item.tag + "<br>";
                        }
                        $this.attr("data-original-title",title)
                    }
                },null,null,false);
                $this.tooltip('toggle')
            })

            $(document).on("click", ".equipment", function () {
                var $this = $(this);
                // var equipmentId = $this.attr("equipmentid");
                // global.get("/web/equipmentMonitor/simpleMonitorPanel/"+equipmentId,function(response){
                //     var equipmentMonitor = response.data.equipmentMonitor;
                //     var title = "";
                //     if(equipmentMonitor!=null){
                //         console.log(equipmentMonitor.length)
                //         for(var i=0;i<equipmentMonitor.length;i++){
                //             var item = equipmentMonitor[i];
                //             title += item.deviceName + ":" + item.data + item.tag + "<br>";
                //         }
                //         $this.attr("data-original-title",title)
                //     }
                // },null,null,false);
                $this.tooltip('toggle')
            })

            $(document).on("dblclick",".equipment", function () {
                global.get("/web/equipmentMonitor/equipmentMonitorPanel/"+$(this).attr("equipmentId"),response=>{
                    var equipmentMonitor = response.data.equipmentMonitor;
                    var list = [];
                    equipmentMonitor.devices.forEach(element=>{
                        var item = {};
                        item.name = element.name;
                        item.value = element.recentData + element.unit;
                        item.stdValue = element.stdValue!=null&&element.stdValue.trim()!=""?element.stdValue+element.unit:"-";
                        item.color = "green"
                        list.push(item);
                    });
                    var data = {
                        title: equipmentMonitor.equipmentName,
                        equipmentImageSrc:global.baseImageUrl+equipmentMonitor.equipmentImg,
                        list: list
                    }
                    Dialog.open({
                        title: "查看设备--"+equipmentMonitor.equipmentName, 
                        theme: "equipmentDialog",
                        width: 900, 
                        height: 'auto',
                        context: self,
                        content: template("equipmentTpl", data),
                        button: [
                            {id:"mybtn1", label:"关闭", intent:"primary"}
                        ]
                    });
                })
            })
            $(document).on("click", "#editTemp", function() {
                var data = $(this).siblings("#temp").text()
                Dialog.open({
                    title: "温度设定", 
                    theme: "tempDialog",
                    width: 320, 
                    height: 'auto',
                    context: self,
                    content: template("tempTpl", {temp: data}),
                    button: [
                        {id:"mybtn1", label:"确定", intent:"primary", click:function(){
                            if (!$("#tempForm").valid()) {
                                return false;
                            }
                            var temp = $("#temp1").val()
                            global.post("/web/rc/waterTemperature?projectId="+project.id + "&waterTemperature="+temp,function(response){
                                if(response.success){
                                    $("#temp").html(temp)
                                    Dialog.toast("操作成功", {"intent":"succss"});
                                }else{
                                    Dialog.toast(response.message, {"intent":"warn"});
                                }
                            });
                        }},
                        {id:"mybtn2", label:"关闭", intent:"primary"}
                    ]
                });
            })
            $(document).on("click", "#modeSwitch", function() {
                if(!$("#modeSwitch span:eq(0)").hasClass("checked")){
                    //切换之后是供冷,切换前是制热
                    global.post("/web/rc/winner?projectId="+project.id,function(response){
                        if(response.success){
                            Dialog.toast("切换成功", {"intent":"succss"});
                        }else{
                            Dialog.toast(response.message, {"intent":"warn"});
                            //变化成切换前状态 1
                            if($("#modeSwitch span:eq(0)").hasClass("checked")){
                                $("#modeSwitch span:eq(1)").addClass("checked");
                                $("#modeSwitch span:eq(0)").removeClass("checked");
                            }else{
                                $("#modeSwitch span:eq(0)").addClass("checked");
                                $("#modeSwitch span:eq(1)").removeClass("checked");
                            }
                        }
                    },null,function(err){
                        //变化成切换前状态
                        Dialog.toast("网络异常", {"intent":"warn"});
                        if($("#modeSwitch span:eq(0)").hasClass("checked")){
                            $("#modeSwitch span:eq(1)").addClass("checked");
                            $("#modeSwitch span:eq(0)").removeClass("checked");
                        }else{
                            $("#modeSwitch span:eq(0)").addClass("checked");
                            $("#modeSwitch span:eq(1)").removeClass("checked");
                        }
                    });
                }else{
                    //切换之后是制热
                    global.post("/web/rc/summer?projectId="+project.id,function(response){
                        if(response.success){
                            Dialog.toast("切换成功", {"intent":"succss"});
                        }else{
                            Dialog.toast(response.message, {"intent":"warn"});
                            //变化成切换前状态
                            if($("#modeSwitch span:eq(1)").hasClass("checked")){
                                $("#modeSwitch span:eq(0)").addClass("checked");
                                $("#modeSwitch span:eq(1)").removeClass("checked");
                            }else{
                                $("#modeSwitch span:eq(1)").addClass("checked");
                                $("#modeSwitch span:eq(0)").removeClass("checked");
                            }
                        }
                    },null,function(err){
                        //变化成切换前状态
                        Dialog.toast("网络异常", {"intent":"warn"});
                        if($("#modeSwitch span:eq(1)").hasClass("checked")){
                            $("#modeSwitch span:eq(0)").addClass("checked");
                            $("#modeSwitch span:eq(1)").removeClass("checked");
                        }else{
                            $("#modeSwitch span:eq(1)").addClass("checked");
                            $("#modeSwitch span:eq(0)").removeClass("checked");
                        }
                    },);
                }

            })
            window.onresize = function () {
                // getTime.resize();
            };
        },
        
    };
    return app;
});